Ext.ns("CRM.SPComp");

	
	var activityFormWin;

	function createActivityForm(leadId, activityId){
		
		var activityValidationCompIds = new Array("activityType","assignedTo","subject","dueDate","duration","opportunity","activityStage","status","priority","reminderDate","activityNotes");
		
		var actionTypeStore=CRM.commons.createComboStore('actionStoreid','activity/activityReqCombo','actionTypes');        
	    var stageStore=CRM.commons.createComboStore('stageStoreid','activity/activityReqCombo','stageTypes');
	    var statusStore=CRM.commons.createComboStore('statusStoreid','activity/activityReqCombo','statusTypes');
	    var priorityStore=CRM.commons.createComboStore('priorityStoreid','activity/activityReqCombo','priorityTypes');

		
		var assignedToStore=CRM.commons.createComboStore('assignedToStoreid','activity/assignedTo','');
		//var opportunitiesTitleStore=CRM.commons.createComboStore('opportunitiesTitleStoreid','activity/opportunitiesTitles?leadId='+leadId,'');
		
        var opportunitiesTitleStore = new Ext.data.JsonStore({
            root 	: 'data',
            fields 	: [ {
            			name 	: 'value',
            			mapping : 'value'
            			}, 
            			{
			            name 	: 'id',
			            mapping : 'id'
			            }
            		  ],
            proxy 	: new Ext.data.HttpProxy({
            method 	: 'GET',
            url 	: 'activity/opportunitiesTitles?leadId='+leadId
            })
          });

        var activityDetailsPanel = {
                xtype       : 'fieldset',
                id          : 'activityDetailsPanel',
                width       : 450,
                height      : 250,
                layout      : 'form',
                labelWidth  : 120,
                items       : [
                               
                    {
						xtype		: 'hidden',
						id			: 'activityLeadId',
						value		: leadId
                    },
                    {
						xtype		: 'hidden',
						id			: 'activityId',
						value		: activityId
                    },
                    {
                        xtype      	: 'combo',
                        fieldLabel 	: 'Activity Type<font color=red>*</font>',
                        id         	: 'activityType',
                        store		: actionTypeStore,
                        value		 : 'SELECT',
                        displayField: 'name',
                        valueField  : 'id',
                        triggerAction:'all',
                        typeAhead	: false,
                        width      	: 250,
                        editable 	: false,
                        autoLoad	: true,
	                    listeners	: {select : function(){
				       						bindValue('activityType', 'activityTypeId');
				       					} 
				       			  }
				   },
				   {
				   		xtype		: 'hidden',
				   		id			: 'activityTypeId'
				   },
                    {
                        xtype      	: 'combo',
                        fieldLabel 	: 'Assigned To<font color=red>*</font>',
                        id         	: 'assignedTo',
                        store		: assignedToStore,
                        value		 : 'SELECT',
                        displayField: 'name',
                        valueField  : 'id',
                        triggerAction:'all',
                        width      	: 250,
                        editable	: false,
                        listeners	: {select : function(){
				       						bindValue('assignedTo', 'assignedToId');
				       					} 
				       			  }
				   },
				   {
				   		xtype		: 'hidden',
				   		id			: 'assignedToId'
				   },
                    {
                        xtype      : 'textfield',
                        fieldLabel : 'Subject<font color=red>*</font>',
                        id         : 'subject',
                        width      : 300
                    },
                    {
                        xtype      : 'datefield',
                        fieldLabel : 'Due Date<font color=red>*</font>',
                        id         : 'dueDate',
                        vtype      : 'daterange',
                        startDateField: 'reminderDate',
                        format     : 'Y-m-d'
                    },
                    {
                        xtype      : 'textfield',
                        fieldLabel : 'Duration (Min.)<font color=red>*</font>',
                        id         : 'duration',
                        width	   : 40,
                        value	   : '0',
                        allowBlank : false
                    },
                    {
                        xtype      	: 'combo',
                        fieldLabel 	: 'Opportunity<font color=red>*</font>',
                        id         	: 'opportunity',
                        store		: opportunitiesTitleStore,
                        value		: 'SELECT',
                        displayField: 'value',
                        valueField  : 'id',
                        triggerAction:'all',
                        value		: "SELECT",	
                        //width      	: 290,
                        editable	: false,
                        //disabled	: true,
                        listeners	: {select : function(){
				       						bindValue('opportunity', 'opportunityId');
				       					} 
				       			  }
				   },
				   {
				   		xtype		: 'hidden',
				   		id			: 'opportunityId'
				   }
                ]
            };

                var notePanel = {
                        xtype       : 'fieldset',
                        id          : 'notePanel',
                        width       : 450,
                        height      : 250,
                        layout      : 'form',
                        labelWidth  : 120,
                        //padding     : '5px',
                        //title		: 'Notes',
                        border      : true,
                        frame       : true,
                        items       : [
                           
                            {
                                xtype      	: 'combo',
                                fieldLabel 	: 'Stage<font color=red>*</font>',
                                id         	: 'activityStage',
                                store		: stageStore,
                                value		 : 'SELECT',
                                displayField: 'name',
                                valueField  : 'id',
                                triggerAction:'all',
                                width      	:  180,
                                editable	: false,
                                listeners	: {select : function(){
						       						bindValue('activityStage', 'activityStageId');
						       					} 
						       			  }
						   },
						   {
						   		xtype		: 'hidden',
						   		id			: 'activityStageId'
						   },
                            {
                                xtype      	: 'combo',
                                fieldLabel 	: 'Status<font color=red>*</font>',
                                id         	: 'status',
                                store		: statusStore,
                                value		 : 'SELECT',
                                displayField: 'name',
                                valueField  : 'id',
                                triggerAction:'all',
                                width      	:  180,
                                editable	: false,
                                listeners	: {select : function(){
						       						bindValue('status', 'statusId');
						       					} 
						       			  }
						   },
						   {
						   		xtype		: 'hidden',
						   		id			: 'statusId'
						   },
                            {
                                xtype      	: 'combo',
                                fieldLabel 	: 'Priority<font color=red>*</font>',
                                id         	: 'priority',
                                store		: priorityStore,
                                value		 : 'SELECT',
                                displayField: 'name',
                                valueField  : 'id',
                                triggerAction:'all',
                                width      	:  180,
                                editable	: false,
                                listeners	: {select : function(){
						       						bindValue('priority', 'priorityId');
						       					} 
						       			  }
						   },
						   {
						   		xtype		: 'hidden',
						   		id			: 'priorityId'
						   },
                            {
                                xtype      : 'checkbox',
                                fieldLabel : 'Reminder',
                                id         : 'reminder'
                            },
                            {
                                xtype      : 'datefield',
                                fieldLabel : 'Reminder Date<font color=red>*</font>',
                                id         : 'reminderDate',
                                vtype      : 'daterange',
                                endDateField: 'dueDate',
                                format     :'Y-m-d'
                            },
                            {
                                xtype  : 'textarea',
                                fieldLabel : 'Notes<font color=red>*</font>',
                                id     : 'activityNotes',
                                width  : 300,
                                height : 70
                            }
                        ]
                    };
                

                var popUpActivityPanel = new Ext.FormPanel({
	            id          : 'popUpActivityPanel',
	            height      : 280,
	            width       : 905,
	            frame       : false,
	            layout      : 'hbox',
	            items       : [activityDetailsPanel,notePanel],
	            scrollable	: true,
	            bbar        : {
				                xtype       : 'toolbar',
				                buttonAlign : 'right',
				                items       : [
											   {
											    xtype   : 'button',
											    id		: 'addButton',
											    text    : 'Save',
											    handler : function(){
											    				var actionValue = Ext.getCmp('addButton').getText();
											    				//addActivity(actionValue);
											    				var form = Ext.getCmp('popUpActivityPanel');
											    				var validationSuccess = simpleFormValidation(form, activityValidationCompIds);
											    				if(validationSuccess == 'true'){
											    					addActivity(actionValue);
											    				}
											    			}
											   },
											   '-',
				                               {
				                                xtype   : 'button',
				                                id		: 'cancelButton',
				                                text    : 'Cancel',
				                                handler	: closeActivityWindow
				                               }
				                            ]
	            		}
                });                

       			activityFormWin = new Ext.Window({
            	title		: 'Create Activity',
            	id			: 'popUpActivityWindow',
            	width		: 920,
            	height		: 315,
            	border		: true,
            	plain		: false,
            	closable	: true,
            	collapsible : true,
            	animCollapse: true,
            	draggable 	: true,
            	maximizable : false,
            	//layout		: 'border',
            	onEsc		: true,
            	model		: true,
            	items		: [popUpActivityPanel]
        		});
            activityFormWin.show(this);
            if(activityId != 0){
            	Ext.getCmp('addButton').setText('Update');
            	showActivityDetailsInPopup(activityId);
            }
            //reloadOpportunity(leadId);
            //alert(leadId);
            validateFormOnLoad(popUpActivityPanel, activityValidationCompIds);
            return activityFormWin;
		};
		
		function reloadOpportunity(selectedLeadId){
			var oppCombo = Ext.getCmp('opportunity');
			oppCombo.setValue(null);
			oppCombo.store.removeAll();
			oppCombo.store.reload({
								params : {leadId : selectedLeadId}
								});
			Ext.getCmp('opportunity').enable();
		};
	
		
		//Date Validation
        Ext.apply(Ext.form.VTypes, {
		daterange : function(val, field) {
			var date = field.parseDate(val);
	 
			if(!date){
				return;
			}
			if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) {
				var start = Ext.getCmp(field.startDateField);
				start.setMaxValue(date);
				start.validate();
				this.dateRangeMax = date;
			} 
			else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) {
				var end = Ext.getCmp(field.endDateField);
				end.setMinValue(date);
				end.validate();
				this.dateRangeMin = date;
			}
			return true;
		   }
	    });
		
		function addActivity(action){
			
		   var message = 'No action taken.';	
		
		   if(action == 'Save'){
        	   message = 'Saved Successfully!';
           }
           if(action == 'Update'){
        	   message = 'Updated Successfully!';
           }
           
		   var formPanel = Ext.getCmp('popUpActivityPanel');
  	       var values = formPanel.getForm().getValues();
  	       var data = Ext.encode(values);
  	       	
      	   Ext.Ajax.request({
      		   url		: 'lead/saveActivity?action='+action,
      		   method	: 'POST',
      		   success	: function(result, request){
      			  			var jsonData = Ext.util.JSON.decode(result.responseText); 
      			  			var responsedActivityId = jsonData.data;
      			   			alert("Activity "+message);
      			   		    Ext.getCmp('activityId').setValue(responsedActivityId);
      			   		    
      			   		    var selectedId = null;
      			   		    if(Ext.getCmp('leadId') != null){
      			   		    	var selectedLeadId = Ext.getCmp('leadId').getValue();
      			   		    	var activityGrd = Ext.getCmp('activitiesGrid');
      			   		    	reloadLeadSubTabs(activityGrd, selectedLeadId);
      			   		    }
      			   		    if(Ext.getCmp('customerId') != null){
      			   		    	var selectedCustomerId = Ext.getCmp('customerId').getValue();
      			   		    	var activityGrd = Ext.getCmp('activitiesGrid');
      			   		    	reloadCustomerSubTabs(activityGrd, selectedCustomerId);
      			   		    }
      			   		    closeActivityWindow();
      			   		  },
      		   failure 	: function(){
      			   			alert("failure");
      			   		  },
      		   jsonData : data   		  
      	   });
		};
		
		
		
		function showActivityDetailsInPopup(activityId){
			var formPanel = Ext.getCmp('popUpActivityPanel');
			var values = formPanel.getForm().getValues();
			var data = Ext.encode(values);
			//alert(data);
			formPanel.getForm().load({
			method  : 'GET',
	            url     : 'activity/showActivityDetailsInPopup?activityId='+activityId,
	      		success : function() {
	            			},
	            failure:function() { 
	                		alert ("Failure");
	               			}
			});
		};
		

		function closeActivityWindow(){
			activityFormWin.close();
		};


//})();	